package com.haiyou.common.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author xiaojie
 * Excel工具类
 */
public class ExcelUtil {

    /**
     * 单页excel导出
     *
     * @param list  需要导出数据
     * @param clazz 导出类
     */
    public static <T> void export(HttpServletResponse response, List<T> list, Class<T> clazz) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("模板.xlsx", StandardCharsets.UTF_8));
        response.setCharacterEncoding("utf-8");
        ExcelWriter excelWriter = null;
        try {
            // 构建一个excel对象
            excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build();
            // 构建一个sheet页
                WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            // 将表头和数据写入表格
            excelWriter.write(list, writeSheet);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * @param list  需要导出数据
     * @param table 自定义表头
     *              new LongestMatchColumnWidthStyleStrategy() 自动设置列宽
     */
    public static <T> void exportCustomTable(HttpServletResponse response, List<T> list, List<String> table) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("模板.xlsx", StandardCharsets.UTF_8));
        response.setCharacterEncoding("utf-8");
        List<List<String>> customTable = new ArrayList<>();
        for (String s : table) {
            List<String> string = new ArrayList<>();
            string.add(s);
            customTable.add(string);
        }
        EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).head(customTable).sheet("easyExcel").doWrite(list);
    }
}
